﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using ServerManager.Classes;
using ServerManager.Network;

namespace ServerManager
{
    public partial class frmConnect : Form
    {
        private DrachamNetwork network;
        private string sessionKey;

        public frmConnect()
        {
            InitializeComponent();
        }

        public DrachamNetwork Network
        {
            get { return network; }
            set { network = value; }
        }

        public string SessionKey
        {
            get { return sessionKey; }
            set { sessionKey = value; }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(this.txtServer.Text) || String.IsNullOrEmpty(this.txtPort.Text) || String.IsNullOrEmpty(this.txtUsername.Text) || String.IsNullOrEmpty(this.txtPassword.Text))
            {
                MessageBox.Show("You must fill in all the fields in this form.", "One or more fields are empty", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            try
            {
                this.network = new DrachamNetwork(IPAddress.Parse(this.txtServer.Text), Int32.Parse(this.txtPort.Text));
            }
            catch
            {
                MessageBox.Show("The specified server could not be reached. It is possible that it is offline.", "Unable to connect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            this.network.NetworkHandler.AddHandler(MessageType.CLoginSuccess, new HandlerMethod(LoginSuccess_Handler));
            this.network.NetworkHandler.AddHandler(MessageType.CLoginFailure, new HandlerMethod(LoginFailure_Handler));
            this.network.Invoke(MessageType.CLoginRequest,
                new NetworkParameter(this.txtUsername.Text, 50),
                new NetworkParameter(this.txtPassword.Text, 50));

            foreach (Control c in this.Controls)
            {
                if (c.GetType() == typeof(Button))
                    c.Enabled = false;
            }
        }

        private void LoginSuccess_Handler()
        {
            this.sessionKey = this.network.ReceiveString(36);
            this.DialogResult = DialogResult.OK;
        }

        private void LoginFailure_Handler()
        {
            MessageBox.Show("You have entered an invalid username and/or password.", "Wrong Username and/or Password", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
}
